package cn.ciis.sys.login;

import cn.ciis.basic.interceptor.AdminAuthInterceptor;
import cn.ciis.basic.interceptor.LoginSessionInterceptor;
import cn.ciis.basic.kit.CiisKit;
import cn.ciis.basic.model.Account;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.common.SSOConstants;
import com.baomidou.kisso.security.token.SSOToken;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;

import java.io.IOException;

/**
 * 登录控制器
 *
 * @author 冉志林
 */
@Clear(AdminAuthInterceptor.class)
public class LoginController extends Controller {

  @Inject LoginService srv;


  /** 显示登录界面 */
  public void index() {

    set("devMode", PropKit.getBoolean("devMode",false));
    createToken("ciis_login_token");
    render("index.html");
  }

  /** 登录 */
  @Before(LoginValidator.class)
  @Clear(LoginSessionInterceptor.class)
  public void doLogin() {

    if(!validateToken("ciis_login_token")){
      renderJson(Ret.fail("msg", "请不要重复提交！"));
      return;
    }

    Boolean keepLogin = getParaToBoolean("keepLogin", false);
    String loginIp = CiisKit.getRealIp(getRequest());
    Ret ret = srv.login(getPara("userName"), getPara("password"),keepLogin, loginIp);
    if (ret.isOk()) {
      String sessionId = ret.getStr(LoginService.SESSION_ID_NAME);
      set(SSOConstants.SSO_COOKIE_MAXAGE, ret.getInt("maxAgeInSeconds"));
      Account loginAccount = ret.getAs(LoginService.LOGIN_ACCOUNT_CACHE_NAME);
      setAttr(LoginService.LOGIN_ACCOUNT_CACHE_NAME, loginAccount);
      // 如果 returnUrl 存在则跳过去，否则跳去首页
      ret.set("returnUrl", getPara("returnUrl", "/admin"));
      SSOHelper.setCookie(getRequest(), getResponse(),  new SSOToken().setId(loginAccount.getId()).setIssuer(sessionId),true);
    }

    renderJson(ret);
  }

  /** 退出登录 */
  @Clear
  @ActionKey("/logout")
  public void logout() {
    SSOToken ssoToken = SSOHelper.getSSOToken(getRequest());

    if(null != ssoToken){
      srv.logout(ssoToken.getIssuer());
      try {
        SSOHelper.logout(getRequest(),getResponse());
      } catch (IOException e) {
        LogKit.error("用户退出登录发生异常！",e);
      }
      //removeCookie(LoginService.SESSION_ID_NAME);
    }



    redirect("/");
  }
}
